﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Xml;

namespace GCPUD.AutoProv
{
    public class AutoProvSettings
    {
        public AutoProvSettings()
        {
            try
            {
                Load();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }

        public string provFileSaveDirectory ="HubConfigFiles";
        public string provServer = "192.168.1.1";
        public int provPort = 1111;
        public string provUser = "default";
        public string provPassword = "default";
        private string configFile;
        private string configFileDirectory;

        private void Load()
        {
            XmlDocument xml = new XmlDocument(); 
            
            string appPath = Form1.FolderPath;
            configFileDirectory = Path.Combine(appPath, "config" + Path.DirectorySeparatorChar);
            configFile = Path.Combine(configFileDirectory, "AutoProv.config");
            if (VerifyDirectory(configFileDirectory) && VerifyFile(configFile))
            {
                LoadConfig(xml, configFile);

                LoadVariables(xml, appPath);
            }
            else
            {
                Console.WriteLine("Using Defaults");
            }
        }

        private static void LoadConfig(XmlDocument xml, string directoryPath)
        {
            Console.WriteLine("AutoProv: Loading config file: {0}", directoryPath);
            System.IO.FileStream fs = new System.IO.FileStream(directoryPath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
            try
            {
                xml.Load(fs);
                fs.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("AutoProv: Continuing with Default Config Values");
                fs.Close();

            }
        }

        private void LoadVariables(XmlDocument xml, string appPath)
        {
            XmlNode xvar;
            try
            {
                //                xml.Load(reader);
                if (xml != null)
                {
                    // Load Variables - Addons
                    xvar = xml.SelectSingleNode("//AutoProv/ConfigFileSaveDirectory");
                    if (xvar != null)
                    {
                        provFileSaveDirectory = Path.Combine(appPath, xvar.InnerText + "\\");

                        Console.WriteLine("AutoProv Load: " + xvar.Name + "=" + provFileSaveDirectory.ToString());
                    }
                    xvar = xml.SelectSingleNode("//AutoProv/Server");
                    if (xvar != null)
                    {
                        provServer = xvar.InnerText;

                        Console.WriteLine("AutoProv Load: " + xvar.Name + "=" + provServer.ToString());
                    }
                    xvar = xml.SelectSingleNode("//AutoProv/Port");
                    if (xvar != null)
                    {
                        provPort = int.Parse(xvar.InnerText);

                        Console.WriteLine("AutoProv Load: " + xvar.Name + "=" + provPort);
                    }
                    xvar = xml.SelectSingleNode("//AutoProv/User");
                    if (xvar != null)
                    {
                        provUser = xvar.InnerText;

                        Console.WriteLine("AutoProv Load: " + xvar.Name + "=" + provUser);
                    }
                    xvar = xml.SelectSingleNode("//AutoProv/Password");
                    if (xvar != null)
                    {
                        provPassword = xvar.InnerText;

                        Console.WriteLine("AutoProv Load: " + xvar.Name + "=" + provPassword);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("AutoProv: PROJECT EXCEPTION, STACK=" + e.StackTrace);
                Console.WriteLine("AutoProv: PROJECT EXCEPTION, SRC=" + e.Source);
                Console.WriteLine("AutoProv: PROJECT : " + e.Message);
            }
            
        }

        private bool VerifyDirectory(string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
            {
                Console.WriteLine("HubProv: Creating config directory");
                try
                {
                    Directory.CreateDirectory(directoryPath);
                    return true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return false;
                }
            }
            else
            {
                return true;
            }
        }

        private bool VerifyFile(string filePath)
        {
            //string directoryPath = Path.GetDirectoryName(filePath);
            if (!File.Exists(filePath))
            {
                try
                {
                    SaveConfigFile(configFile);
                    return true;

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return false;
                }
            }
            else return true;
        }
        public void Save()
        {
            SaveConfigFile(configFile);

        }
        private void SaveConfigFile(string sPath)
        {
            XmlDocument xml;
            XmlElement root;
            XmlElement element;
            XmlText text;
            XmlComment xmlComment;

            //sPath = Path.Combine(sPath, "HubProv.config");

            xml = new XmlDocument();
            XmlDeclaration dc = xml.CreateXmlDeclaration("1.0", "utf-8", null);
            xml.AppendChild(dc);

            xmlComment = xml.CreateComment(
                "=======================================================================\n" +
                ".CONFIG  -  This is the Config File For Provisioning\n\n" +
                "XML file containing settings to customize in \n" +
                "========================================================================");

            //let's add the root element
            root = xml.CreateElement("AutoProv");
            root.AppendChild(xmlComment);
            //let's add another element (child of the root)
            element = xml.CreateElement("ConfigFileSaveDirectory");
            text = xml.CreateTextNode(provFileSaveDirectory);
            element.AppendChild(text);
            root.AppendChild(element);
            
            element = xml.CreateElement("Server");
            text = xml.CreateTextNode(provServer);
            element.AppendChild(text);
            root.AppendChild(element);

            element = xml.CreateElement("Port");
            text = xml.CreateTextNode(provPort.ToString());
            element.AppendChild(text);
            root.AppendChild(element);

            element = xml.CreateElement("User");
            text = xml.CreateTextNode(provUser);
            element.AppendChild(text);
            root.AppendChild(element);

            element = xml.CreateElement("Password");
            text = xml.CreateTextNode(provPassword);
            element.AppendChild(text);
            root.AppendChild(element);

            xml.AppendChild(root);

            System.IO.FileStream fs = new System.IO.FileStream(@sPath, System.IO.FileMode.Create,
                                                               System.IO.FileAccess.Write);
            try
            {
                xml.Save(fs);
                fs.Close();
            }
            catch (Exception np)
            {
                Console.WriteLine(np.Message);
            }
        }
    }
}
